#include "server_functions.h"
#include <errno.h>

// 主函数
int main(int argc, char *argv[]) {
    SOCKET server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    int addr_len = sizeof(client_addr);
    char buffer[BUFFER_SIZE];

    // Linux下不需要Winsock初始化

    // 创建套接字
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == INVALID_SOCKET) {
        printf("Socket creation failed: %d\n", errno);
        return 1;
    }

    // 设置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(config.port);

    // 绑定套接字
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
        printf("Bind failed: %d\n", errno);
        close(server_socket);
        return 1;
    }

    // 监听连接
    if (listen(server_socket, config.max_connections) == SOCKET_ERROR) {
        printf("Listen failed: %d\n", errno);
        close(server_socket);
        return 1;
    }

    printf("Lightweight HTTP Server v%s running on port %d\n", SERVER_VERSION, config.port);
    printf("Document root: %s\n", config.document_root);
    printf("Press Ctrl+C to stop the server\n");

    // 主循环，处理客户端连接
    while (1) {
        // 接受客户端连接
        client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &addr_len);
        if (client_socket == INVALID_SOCKET) {
            printf("Accept failed: %d\n", errno);
            continue;
        }

        // 接收HTTP请求
        memset(buffer, 0, BUFFER_SIZE);
        if (recv(client_socket, buffer, BUFFER_SIZE - 1, 0) == SOCKET_ERROR) {
            printf("Receive failed: %d\n", errno);
            close(client_socket);
            continue;
        }

        // 解析HTTP请求
        char *method = NULL, *path = NULL, *query = NULL;
        parse_http_request(buffer, &method, &path, &query);

        // 处理请求
        if (method && path) {
            if (strcmp(method, "GET") == 0) {
                handle_get_request(client_socket, path, query);
            } else if (strcmp(method, "POST") == 0) {
                // 提取POST内容和Content-Type
                char *content_start = strstr(buffer, "\r\n\r\n");
                char *content = (content_start) ? content_start + 4 : "";
                
                // 提取Content-Type头
                char *content_type = NULL;
                char *type_start = strstr(buffer, "Content-Type:");
                if (!type_start) {
                    type_start = strstr(buffer, "content-type:");
                }
                
                if (type_start) {
                    type_start += 13; // 跳过"Content-Type:"
                    while (*type_start == ' ') type_start++; // 跳过空格
                    
                    char *type_end = strstr(type_start, "\r\n");
                    if (type_end) {
                        size_t type_len = type_end - type_start;
                        content_type = malloc(type_len + 1);
                        if (content_type) {
                            strncpy(content_type, type_start, type_len);
                            content_type[type_len] = '\0';
                        }
                    }
                }
                
                printf("[DEBUG] POST Content-Type: %s\n", content_type ? content_type : "none");
                
                // 检查是否为文件上传请求
                if (content_type && strstr(content_type, "multipart/form-data")) {
                    if (strcmp(path, "/upload") == 0) {
                        printf("[DEBUG] Processing file upload request\n");
                        handle_file_upload(client_socket, content, content_type);
                    } else {
                        // 其他multipart请求，返回错误
                        send_json_response(client_socket, 
                            "{\"error\":\"Multipart uploads only supported at /upload\"}", 400);
                    }
                } else {
                    // 常规POST请求处理
                    handle_post_request(client_socket, path, content);
                }
                
                free(content_type);
            } else if (strcmp(method, "OPTIONS") == 0) {
                // 处理CORS预检请求
                char cors_response[] = 
                    "HTTP/1.1 200 OK\r\n"
                    "Access-Control-Allow-Origin: *\r\n"
                    "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n"
                    "Access-Control-Allow-Headers: Content-Type\r\n"
                    "Content-Length: 0\r\n"
                    "Connection: close\r\n"
                    "\r\n";
                send(client_socket, cors_response, strlen(cors_response), 0);
            }
        }

        // 释放资源
        free(method);
        free(path);
        free(query);

        // 关闭客户端连接
        close(client_socket);
    }

    // 清理资源
    close(server_socket);
    return 0;
}